package com.yueya.media.mongo.impl;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.gridfs.GridFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
public class MongodbFactory {

    @Autowired
    private MongoTemplate mongoTemplate;

    private GridFS gridFS;

    private DBCollection dbCollection;

    public GridFS getGridFS(String bucket) {
        if (gridFS != null && gridFS.getBucketName().equals(bucket)) {
            return gridFS;
        }
        DB db = mongoTemplate.getMongoDbFactory().getLegacyDb();
        if (bucket == null) {
            gridFS = new GridFS(db);
        } else {
            gridFS = new GridFS(db, bucket);
        }
        return gridFS;
    }

    public DBCollection getDbCollection(String collectionName) {
        if (dbCollection != null && dbCollection.getFullName().equals(collectionName)) {
            return dbCollection;
        }
        DB db = mongoTemplate.getMongoDbFactory().getLegacyDb();
        if (collectionName == null) {
            return null;
        } else {
            dbCollection = db.getCollection(collectionName);
        }
        return dbCollection;
    }
}
